package com.edou.cms.controller.admin;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.json.simple.JSONObject;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.edou.base.controller.BaseController;
import com.edou.base.token.TokenValidate;
import com.edou.cms.entity.CmsArticle;
import com.edou.cms.entity.CmsArticleTag;
import com.edou.cms.entity.CmsBlogArticle;
import com.edou.cms.entity.CmsBlogAuthor;
import com.edou.cms.entity.CmsChannel;
import com.edou.cms.entity.CmsTag;
import com.edou.cms.form.CmsArticleForm;
import com.edou.cms.form.CmsBlogArticleForm;
import com.edou.cms.service.ICmsArticleService;
import com.edou.cms.service.ICmsArticleTagService;
import com.edou.cms.service.ICmsBlogArticleService;
import com.edou.cms.service.ICmsBlogAuthorService;
import com.edou.cms.service.ICmsBlogAuthorTagService;
import com.edou.cms.service.ICmsChannelService;
import com.edou.cms.service.ICmsTagService;


@Controller("cmsBlogArticleController")
@Scope("prototype")
@RequestMapping("/admin/cms/blog/article")
public class CmsBlogArticleController extends BaseController {

	@Resource(name = "cmsBlogArticleServiceImpl")
	private ICmsBlogArticleService cmsBlogArticleService;

	@Resource
	private ICmsChannelService cmsChannelService;

	@Resource
	private ICmsTagService cmsTagService;
	
	@Resource
	private ICmsArticleService cmsArticleService;
	
	@Resource(name = "cmsBlogAuthorServiceImpl")
	private ICmsBlogAuthorService cmsBlogAuthorService;
	
	@Resource(name = "cmsBlogAuthorTagServiceImpl")
	private ICmsBlogAuthorTagService cmsBlogAuthorTagService;
	
	@Resource(name = "cmsArticleTagServiceImpl")
	private ICmsArticleTagService cmsArticleTagService;
	
	/**
	 * 首页
	 * @return 
	 */
	@RequestMapping(value = "/index.htm", method = RequestMethod.GET)
	public ModelAndView index(@ModelAttribute CmsBlogArticleForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/cms/cms_blog_article_index");
		Map<String, Object> data = view.getModel();
		data.put("authorType", model.getAuthorType());
		return view;
	}

	/**
	 * 分页查询
	 * @return 
	 */
	@RequestMapping(value = "/listCmsBlogArticleByPage.htm", method = RequestMethod.POST)
	public void listCmsBlogArticleByPage(@ModelAttribute CmsBlogArticleForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		try{
			cmsBlogArticleService.listCmsBlogArticleByPage(model.getPageResult(),model.getCondition());
			JSONObject root = toPageJson(model.getPageResult(), new String[]{"id","authorId","articleId"});
			ajaxPageResult(root,response);
		}catch(Exception ex){
			String msg = "查询博客内的相关文章时发生异常："+ex.getMessage();
			logger.error(msg,ex);
		}
	}

	/**
	 * 保存博客内的相关文章-跳转页面
	 * @return 
	 */
	@RequestMapping(value = "/edit.htm", method = RequestMethod.GET)
	public ModelAndView edit(@ModelAttribute CmsArticleForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/cms/cms_blog_article_add");
		Map<String,Object> data = view.getModel();
		StringBuffer strs = new StringBuffer();
		String str = "";
		if(StringUtils.isNotBlank(model.getItem().getId())){
			// 根据文章id获取文章对象
//			CmsArticle item = cmsArticleService.getArticleById(model.getItem().getId());
			CmsArticle item = cmsArticleService.getBlogArticleById(model.getItem().getId());
			// 根据文章id获取cms_blog_article 博客内的相关文章 的一个对象
			CmsBlogArticle cmsBlogArticle = cmsBlogArticleService.getCmsBlogArticleByArticleId(model.getItem().getId());
			if(cmsBlogArticle !=null){
				// 将博主id赋值给文章表的非保留字段BlogId
				item.setBlogId(cmsBlogArticle.getAuthorId());
				// 博主根据博主id获取到博主的一个对象
				CmsBlogAuthor cmsBlogAuthor = cmsBlogAuthorService.getCmsBlogAuthorById(cmsBlogArticle.getAuthorId());
				if(cmsBlogAuthor !=null){
					// 将博主name赋值给文章表的非保留字段BlogName
					item.setBlogName(cmsBlogAuthor.getName());
					List<CmsArticleTag> cmsArticleTagList = cmsArticleTagService.listCmsArticleTagByArticleId(model.getItem().getId());
					for (CmsArticleTag cmsArticleTag : cmsArticleTagList) {
						str = strs.append(cmsArticleTag.getTagId()+",").toString();
					}
					item.setTagList(str);
				}
			}
			//查询标签
			List<CmsTag> cmsTagList = cmsTagService.listCmsTagAll();
			data.put("cmsTagList", cmsTagList);
			data.put("item", item);
			
			// 传递参数
			data.put("authorType", model.getAuthorType());
		}
		return view;
	}

	/**
	 * 保存博客内的相关文章
	 * @return 
	 */
	@RequestMapping(value = "/saveCmsBlogArticle.htm", method = RequestMethod.POST)
	@TokenValidate
	public ModelAndView saveRole(@ModelAttribute CmsArticleForm model,HttpServletRequest request,HttpSession session){
		try {
			if(StringUtils.isBlank(model.getItem().getId())){
				CmsArticle item = model.getItem();
				item.setChannelId("-");
				// 首先进行保存网站文章表
				cmsArticleService.doSave(item);
				// 保存博客内的相关文章
				CmsBlogArticle cmsBlogArticle = new CmsBlogArticle();
				cmsBlogArticle.setArticleId(item.getId());
				cmsBlogArticle.setAuthorId(model.getItem().getBlogId());
				cmsBlogArticle.setType(model.getAuthorType());
				cmsBlogArticleService.add(cmsBlogArticle);
			}else{
				CmsArticle item = cmsArticleService.getArticleById(model.getItem().getId());
				if(item != null){
					item.setName(model.getItem().getName());
					item.setTagList(model.getItem().getTagList());
					item.setSort(model.getItem().getSort());
					item.setSummary(model.getItem().getSummary());
					item.setContent(model.getItem().getContent());
					item.setBlogId(model.getItem().getBlogId());
					cmsArticleService.doUpdate(item);
				}
			}
			return ajaxJSON(Status.success,"保存成功");
		} catch (Exception e) {
			String msg = "保存博客内的相关文章时发生异常：" + e.getMessage();
			logger.error(msg,e);
			return ajaxJSON(Status.error, "保存失败，请稍后重试");
		}
	}
	/**
	 * 删除CmsBlogArticle
	 * @return 
	 */
	@RequestMapping(value = "/del.htm", method = RequestMethod.POST)
	public ModelAndView del(@ModelAttribute CmsBlogArticleForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		try {
			cmsBlogArticleService.delByIds(model.getSelIds().split(","));
			return ajaxJSON(Status.success,"删除成功");
		} catch (Exception e) {
			String msg = "删除博客内的相关文章时发生异常：" + e.getMessage();
			logger.error(msg,e);
			return ajaxJSON(Status.error, "删除失败，请稍后重试");
		}
	}

	/**
	 * 跳转到添加文章界面
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/to_add.htm", method = RequestMethod.GET)
	public ModelAndView toAdd(CmsArticleForm model) {
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/cms/cms_blog_article_add");
		Map<String,Object> data = view.getModel();
		if(model.getItem()!= null && model.getItem().getChannelId()!= null && StringUtils.isNotBlank(model.getItem().getChannelId())){
			CmsChannel channel = cmsChannelService.getCmsChannelById(model.getItem().getChannelId());
			model.getItem().setChannelName(channel.getName());
		}
		//查询标签
		List<CmsTag> cmsTagList = cmsTagService.listCmsTagAll();
		data.put("cmsTagList", cmsTagList);
		data.put("item", model.getItem());
		
		// 传递参数
		data.put("authorType", model.getAuthorType());
		
		return view;
	}

}

